package com.example.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import org.json.JSONException;
import org.json.JSONObject;

import com.exanple.data.Activeinfo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class Agreerec extends Service {
	private boolean isRun;// 线程是否继续的标志
	public static final String bm = "utf-8";
	private static JSONObject activeInfo;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
  @Override
public int onStartCommand(Intent intent, int flags, int startId) {
	  isRun=true;
	  new Thread(new Runnable() {
			@Override
			// 在Runnable中，如果要让线程自己一直跑下去，必须自己定义while结构
			// 如果这个run()方法读完了，则整个线程自然死亡
			public void run() {
				// 定义一个线程中止标志
            
				try {

					ServerSocket serverSocket = new ServerSocket(47777);
					while (isRun) {
						Socket client = serverSocket.accept();
						BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), bm));
						String str = in.readLine();
						activeInfo=new JSONObject(str);
						Activeinfo.activelist.add(new Activeinfo(activeInfo.getString("活动名"), activeInfo.getString("参与者"), "2017.6.9"));
					}
				}catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 

			}
		}).start();// 默认线程不启动，必须自己start()
	  return START_STICKY;
}
  @Override
public void onDestroy() {
	// TODO Auto-generated method stub
	super.onDestroy();
	isRun=false;
}
}
